package com.it.jzs.handle;

import cn.hutool.jwt.JWT;
import com.it.jzs.util.CommentThreadLocal;
import com.it.jzs.vo.BlogCommentVo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class AuthInterceptor implements HandlerInterceptor {
    // 密钥
    private final String SLOT = "jzs";   // MD5加盐

    byte[] key = "1234567890".getBytes();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//       if (request.get)
        if (request.getRequestURL().toString().contains("/comment")){  // 如果路径中包含comment，就不需要拦截了
            return true;
        }
        System.out.println("request.getRequestURL() = " + request.getRequestURL());
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("Method:OPTIONS");
            return true;
        }

        String authorization = request.getHeader("Authorization");
        // 密钥
        byte[] key = SLOT.getBytes();

// 默认验证HS265的算法
        boolean validate = JWT.of(authorization).setKey(key).validate(0);
//        System.out.println("validate = " + validate);
        if (validate) {
            return true;
        }
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        List<BlogCommentVo> commentVos = CommentThreadLocal.get();
        if (commentVos != null) {  // 线程私有的，如果存在才进行删除操作
            System.out.println("thread");
            CommentThreadLocal.remove();

        }
    }
}
